package com.hepinghospital.user.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ainemo.sdk.otf.ConnectNemoCallback;
import com.ainemo.sdk.otf.LoginResponseData;
import com.ainemo.sdk.otf.NemoSDK;
import com.alibaba.fastjson.JSONObject;
import com.hepinghospital.user.R;
import com.hepinghospital.user.adapter.HomeDeptAdapter;
import com.hepinghospital.user.adapter.RollViewAdapter;
import com.hepinghospital.user.base.BaseApplication;
import com.hepinghospital.user.base.BaseFragment;
import com.hepinghospital.user.eventbus.VersionUpdateEvent;
import com.hepinghospital.user.ui.NewsActivity;
import com.hepinghospital.user.ui.PayActivity;
import com.hepinghospital.user.ui.activity.graphic.graphicSelect.GraphicSelectActivity;
import com.hepinghospital.user.ui.activity.home.BookDoctorByDateActivity;
import com.hepinghospital.user.ui.activity.home.DoctorDetailActivity;
import com.hepinghospital.user.ui.activity.home.DrugDirectoryActivity;
import com.hepinghospital.user.ui.activity.home.HomeDeptMoreActivity;
import com.hepinghospital.user.ui.activity.home.SearchDoctorActivity;
import com.hepinghospital.user.ui.activity.home.TeamListActivity;
import com.hepinghospital.user.ui.activity.nursing.AppointProjectListActivity;
import com.hepinghospital.user.ui.dialog.GuideDialog;
import com.hepinghospital.user.ui.dialog.UpdateDialog;
import com.hepinghospital.user.ui.kotlin.DailyRegisterActivity;
import com.hepinghospital.user.util.HarmonyUtil;
import com.hepinghospital.user.util.ImageLoaderHelper;
import com.hepinghospital.user.util.ToastUtil;
import com.jude.rollviewpager.RollPagerView;
import com.jude.rollviewpager.hintview.ColorPointHintView;
import com.rest.business.RestProxy;
import com.rest.constant.JDConstant;
import com.rest.observer.BaseObserver;
import com.rest.response.BannerListResponse;
import com.rest.response.CloudDoctorResponse;
import com.rest.response.Doctor;
import com.rest.response.HomeDeptResponse;
import com.rest.response.VersionResponse;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;
import jz.joyoung.robot.util.DpUtil;
import jz.joyoung.robot.util.LogUtil;
import jz.joyoung.robot.util.UIConstants;
import jz.joyoung.robot.util.UtilList;
import jz.joyoung.robot.util.UtilString;

/**
 * 首页
 *
 * @author Administrator
 * @date 2020/2/9
 */

public class HomeFragment extends BaseFragment {
    @BindView(R.id.doctor_recyclerView)
    RecyclerView rvDoctor;
    @BindView(R.id.rpv_banner)
    RollPagerView rpvBanner;
    @BindView(R.id.refreshLayout)
    RefreshLayout refreshLayout;
    @BindView(R.id.rv_home_dept)
    RecyclerView rvHomeDept;
    @BindView(R.id.iv_unread)
    ImageView ivUnread;
    @BindView(R.id.tv_drug_directory)
    TextView tvDrugDirectory;
    @BindView(R.id.btn_dept_more)
    TextView btnDeptMore;
    @BindView(R.id.btn_more)
    TextView btnMore;

    private List<Doctor> doctorList = new ArrayList<>();
    private List<HomeDeptResponse> listDept = new ArrayList<>();
    private DoctorAdapter doctorAdapter;
    private List<BannerListResponse.Header> listBannerHead = new ArrayList<>();

    private HomeDeptAdapter homeDeptAdapter;
    private UpdateDialog mUpdateDialog;
    private GuideDialog guideDialog;
    private RollViewAdapter rollViewAdapter;
    @SuppressLint("StaticFieldLeak")
    private static HomeFragment homeFragment;

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView() {
        GridLayoutManager managerDept = new GridLayoutManager(mContext, 4);
        rvHomeDept.setLayoutManager(managerDept);
        homeDeptAdapter = new HomeDeptAdapter(mContext, listDept);
        rvHomeDept.setAdapter(homeDeptAdapter);
        if (rvHomeDept.getItemDecorationCount() == 0) {
            rvHomeDept.addItemDecoration(new RecyclerView.ItemDecoration() {
                @Override
                public void onDraw(@NonNull Canvas c, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                    super.onDraw(c, parent, state);
                }

                @Override
                public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                    super.getItemOffsets(outRect, view, parent, state);
                    outRect.right = DpUtil.dip2px(requireActivity(), 3);
                    outRect.left = DpUtil.dip2px(requireActivity(), 3);
                    outRect.bottom = DpUtil.dip2px(requireActivity(), 12);
                }
            });
        }
        //找医生
        LinearLayoutManager manager = new LinearLayoutManager(mContext);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        rvDoctor.setLayoutManager(manager);
        doctorAdapter = new DoctorAdapter();
        rvDoctor.setAdapter(doctorAdapter);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(refreshlayout -> {
            doctorList.clear();
            initData();
        });
        //设置圆点指示器颜色
        rpvBanner.setHintView(new ColorPointHintView(mContext, 0xFFFFFFFF, 0x7FFFFFFF));
        //设置适配器
        rollViewAdapter = new RollViewAdapter(mContext, listBannerHead);
        rpvBanner.setAdapter(rollViewAdapter);
        //顶部轮播图点击
        rpvBanner.setOnItemClickListener(position -> {
            BannerListResponse.Header header = listBannerHead.get(position);
            if ("web".equals(header.jumpMode)) {
                Bundle bundle = new Bundle();
                bundle.putString("url", header.target);
                startActivity(NewsActivity.class, bundle);
            } else if ("miniApp".equals(header.jumpMode)) {
                JSONObject jsonObject = JSONObject.parseObject(header.target);
//                    String type = jsonObject.getString( "type" );
                String path = jsonObject.getString("url");
                String APPID = jsonObject.getString("APPID");
                String appid = jsonObject.getString("appid");
                Log.e("小程序---", appid + "---" + path + "---" + APPID);
                IWXAPI api = WXAPIFactory.createWXAPI(mContext, APPID);
                WXLaunchMiniProgram.Req req = new WXLaunchMiniProgram.Req();
                req.userName = appid; // 填小程序原始id gh_021419dddadc
                req.path = path;                  ////拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。
                req.miniprogramType = WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE;// 可选打开 开发版，体验版和正式版
                api.sendReq(req);
            }
        });
    }

    @Override
    protected void initData() {
        getDoctorList();
        getVersion();
        getHomeDeptList();
        getBannerList();
        xyLogin();
    }

    //小鱼登录
    private void xyLogin() {
        NemoSDK.getInstance().loginXYlinkAccount(BaseApplication.xyAccount, BaseApplication.xyPassword, new ConnectNemoCallback() {

            @Override
            public void onFailed(String s) {
                BaseApplication.isXYLogin = false;
                LogUtil.e("小鱼登陆失败错误码：$errorCode" + s);
            }

            @Override
            public void onSuccess(LoginResponseData loginResponseData, boolean b) {
                BaseApplication.isXYLogin = true;
                LogUtil.e("小鱼登陆成功");
            }

            @Override
            public void onNetworkTopologyDetectionFinished(LoginResponseData loginResponseData) {

            }
        });
    }


    @OnClick({R.id.edt_search, R.id.tv_drug_directory, R.id.btn_dept_more, R.id.btn_more, R.id.ll_outpatient_appointment,
            R.id.ll_nursing_appointment, R.id.ll_online_consultation, R.id.ll_cloud_based_clinic, R.id.ll_team_consultation, R.id.ll_health_insurance})
    public void onViewClicked(View view) {
        Bundle bundle = new Bundle();
        switch (view.getId()) {
            case R.id.edt_search:
            case R.id.btn_more:
                bundle.putInt("type", 0);
                startActivity(SearchDoctorActivity.class, bundle);
                break;
            case R.id.tv_drug_directory:
                startActivity(new Intent(mContext, DrugDirectoryActivity.class));
                break;
            case R.id.btn_dept_more:
                startActivity(new Intent(mContext, HomeDeptMoreActivity.class));
                break;
            case R.id.ll_outpatient_appointment:
                startActivity(DailyRegisterActivity.class);
                break;
            case R.id.ll_nursing_appointment:
                startActivity(new Intent(mContext, AppointProjectListActivity.class));
                break;
            case R.id.ll_online_consultation:
                //在线问诊/图文问诊
                bundle.putInt("type", 1);
                startActivity(SearchDoctorActivity.class, bundle);
//                startActivity(BookDoctor2Activity.class, bundle);
                break;
            case R.id.ll_cloud_based_clinic:
                ToastUtil.showToastCenter(mContext,"功能暂未开通");
//                bundle.putInt("type", 3);
//                startActivity(BookDoctorByDateActivity.class, bundle);
                break;
            case R.id.ll_team_consultation:
                startActivity(TeamListActivity.class);
                break;
            case R.id.ll_health_insurance:
                IWXAPI api = WXAPIFactory.createWXAPI(mContext, JDConstant.APP_ID);
                WXLaunchMiniProgram.Req req = new WXLaunchMiniProgram.Req();
                req.userName = "gh_021419dddadc"; // 填小程序原始id gh_021419dddadc
                req.miniprogramType = WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE;// 可选打开 开发版，体验版和正式版
//                req.path =                   ////拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。
                api.sendReq(req);
                break;
            default:
                break;
        }
    }

    class DoctorAdapter extends RecyclerView.Adapter<DoctorAdapter.Holder> {

        @NotNull
        @Override
        public Holder onCreateViewHolder(@NotNull ViewGroup parent, int viewType) {
            return new Holder(LayoutInflater.from(mContext).inflate(R.layout.item_book_doctor_online2, parent, false));
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(Holder holder, final int position) {
            holder.itemView.setOnClickListener(v -> {
                Bundle bundle = new Bundle();
                bundle.putString("id", doctorList.get(position).id);
                bundle.putInt(UIConstants.DOCTORDETAILACTIVITY_TYPE_FLAG, UIConstants.DOCTORDETAILACTIVITY_TYPE_0);
                startActivity(DoctorDetailActivity.class, bundle);
            });
            holder.tv_level.setText(doctorList.get(position).jobTitleName);
            holder.tv_skill.setText("擅长:" + doctorList.get(position).docGoodAtNames);
            holder.tv_star.setText(doctorList.get(position).score);
            holder.tv_name.setText(doctorList.get(position).docName);
            if (!UtilString.isEmpty(doctorList.get(position).thumbnailUrl)) {
                ImageLoaderHelper.getInstance().GlideCircleImageLoader(mContext, doctorList.get(position).thumbnailUrl, holder.img_head);
            } else {
                holder.img_head.setImageResource(R.mipmap.img_default);
            }

            if (doctorList.get(position).isPrescription == 1) {
                holder.tv_recipel.setVisibility(View.VISIBLE);
                holder.tv_recipel.setText("处方");
//                holder.tv_recipel.setTextColor(Color.parseColor("#ffffff"));
            } else {
                holder.tv_recipel.setVisibility(View.GONE);
                holder.tv_recipel.setText("非处方");
//                holder.tv_recipel.setTextColor(Color.parseColor("#ffd5d5d5"));
            }
            if (!UtilString.isEmpty(doctorList.get(position).num)) {
                holder.tv_turnNum.setVisibility(View.VISIBLE);
                holder.tv_turnNum.setText("" + doctorList.get(position).num);
            } else {
                holder.tv_turnNum.setVisibility(View.GONE);
            }
            if (!UtilString.isEmpty(doctorList.get(position).deptName)) {
                holder.tv_deptName.setText(doctorList.get(position).deptName);
            } else {
                holder.tv_deptName.setVisibility(View.GONE);
            }
            holder.tvRecommend.setVisibility(View.GONE);
//            if ("0".equals(doctorList.get(position).isRecommend)) {
//                holder.tvRecommend.setVisibility(View.GONE);
//            } else {
//                holder.tvRecommend.setVisibility(View.VISIBLE);
//            }
            float rate = doctorList.get(position).score.isEmpty() ? 0f : Float.parseFloat(doctorList.get(position).score);
            holder.tv_star.setText(rate + "");
            holder.btn_yuyue.setOnClickListener(v -> {
                Bundle bundleCloud = new Bundle();
                bundleCloud.putSerializable(UIConstants.OBJ_Doctor, doctorList.get(position));
                bundleCloud.putInt(UIConstants.PayActivity_TYPE_FLAG, UIConstants.PayActivity_TYPE_1);
                startActivity(PayActivity.class, bundleCloud);
            });
            holder.btn_zixun.setOnClickListener(v -> {
                //图文问诊
                Bundle bundle = new Bundle();
                bundle.putSerializable(UIConstants.OBJ_Doctor, doctorList.get(position));
                bundle.putInt(UIConstants.PayActivity_TYPE_FLAG, UIConstants.PayActivity_TYPE_0);
                startActivity(GraphicSelectActivity.class, bundle);
            });

            //0:图文咨询和云门诊 1：图文咨询 3:云门诊
            if (doctorList.get(position).diagType == 0) {
                holder.btn_yuyue.setVisibility(View.VISIBLE);
                holder.btn_zixun.setVisibility(View.VISIBLE);
            } else if (doctorList.get(position).diagType == 1) {
                holder.btn_yuyue.setVisibility(View.GONE);
                holder.btn_zixun.setVisibility(View.VISIBLE);
            } else if (doctorList.get(position).diagType == 3) {
                holder.btn_yuyue.setVisibility(View.VISIBLE);
                holder.btn_zixun.setVisibility(View.GONE);
            } else {
                holder.btn_yuyue.setVisibility(View.GONE);
                holder.btn_zixun.setVisibility(View.GONE);
            }
        }

        @Override
        public int getItemCount() {
            return doctorList.size();
        }

        class Holder extends RecyclerView.ViewHolder {

            TextView tv_name, tv_level, tv_recipel, tv_deptName, tv_skill, tv_star, btn_yuyue, btn_zixun, tv_turnNum, tvRecommend;
            ImageView img_head;

            public Holder(View itemView) {
                super(itemView);
                tv_name = itemView.findViewById(R.id.tv_name);
                tv_level = itemView.findViewById(R.id.tv_level);
                tv_recipel = itemView.findViewById(R.id.tv_recipel);
                tv_deptName = itemView.findViewById(R.id.tv_deptName);
                tv_skill = itemView.findViewById(R.id.tv_skill);
                tv_star = itemView.findViewById(R.id.tv_star);
                img_head = itemView.findViewById(R.id.img_head);
                btn_yuyue = itemView.findViewById(R.id.btn_yuyue);
                btn_zixun = itemView.findViewById(R.id.btn_zixun);
                tv_turnNum = itemView.findViewById(R.id.tv_turn_num);
                tvRecommend = itemView.findViewById(R.id.iv_recommend);

            }
        }
    }

    /**
     * 找科室接口请求
     *
     * @time 2021/1/5 9:34
     */
    private void getHomeDeptList() {
        RestProxy.getInstance().getHomeDeptList("0", new BaseObserver<List<HomeDeptResponse>>() {
            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(getActivity(), e);
            }


            @Override
            public void onSuccess(List<HomeDeptResponse> homeDeptResponse) {
                Log.e("首页找科室---", homeDeptResponse.size() + "");
                try {
                    listDept.clear();
                    listDept.addAll(homeDeptResponse.subList(0, 8));
                    homeDeptAdapter.notifyDataSetChanged();
                } catch (Exception e) {
                    // 捕获异常，如果要捕获Json数据异常，写catch(JSONException e)
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 获取推荐医生列表
     */
    private void getDoctorList() {
        RestProxy.getInstance().getCloudDoctorList("", "", "", "", "1", "1", "10", "1", "", "", new BaseObserver<CloudDoctorResponse>() {
            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(mContext, e);
                refreshLayout.finishRefresh(false);
            }

            @Override
            public void onSuccess(CloudDoctorResponse result) {
                LogUtil.d("__result", " " + result.records.size());
                doctorList.clear();
                doctorList.addAll(result.records);
                doctorAdapter.notifyDataSetChanged();
                refreshLayout.finishRefresh(true);
            }
        });
    }


    @Override
    public void onPause() {
        super.onPause();
        rpvBanner.pause();
    }

    @Override
    public void onResume() {
        super.onResume();
        rpvBanner.resume();
    }


    private void getVersion() {
        RestProxy.getInstance().getVersion(new BaseObserver<VersionResponse>() {
            @Override
            public void onSuccess(VersionResponse versionResponse) {
                PackageManager pm = mContext.getPackageManager();
                PackageInfo pi;
                String versionName = "";
                int versionCode = 0;
                try {
                    pi = pm.getPackageInfo(mContext.getPackageName(), 0);
                    versionCode = pi.versionCode;
                    versionName = pi.versionName;
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }
                if (versionResponse.vision > versionCode && versionResponse.isUpdate == 1) {
                    if (HarmonyUtil.readPureModeState(mContext) == 1) {
                        showCodeDialog(versionResponse.url, versionResponse.isUpdate);
                    } else {
                        showPureModeDialog();
                    }
                }
                EventBus.getDefault().postSticky(new VersionUpdateEvent(versionResponse.url, versionName, versionResponse.vision > versionCode));
            }
        });
    }

    /**
     * 首页轮播图
     *
     * @time 2020/12/10 15:13
     */
    private void getBannerList() {
        RestProxy.getInstance().getBannerList(new BaseObserver<BannerListResponse>() {
            @Override
            public void onSuccess(BannerListResponse bannerListResponse) {
                try {
                    if (!UtilList.isEmpty(bannerListResponse.header)) {
                        listBannerHead.clear();
                        listBannerHead.addAll(bannerListResponse.header);
                        rollViewAdapter.notifyDataSetChanged();
                    }
                } catch (Exception e) {
                    // 捕获异常，如果要捕获Json数据异常，写catch(JSONException e)
                    e.printStackTrace();
                    //打印出来就Log.e(TAG,Log.getStackTraceString(e));
                }
            }
        });
    }

    private void showPureModeDialog() {
        guideDialog = GuideDialog.newInstance();
        guideDialog.setmListener(new GuideDialog.OnItemClickListener() {
            @Override
            public void onConfirm() {
                Intent intent = new Intent(Settings.ACTION_SETTINGS);
                startActivity(intent);
            }

            @Override
            public void onCancel() {

            }
        });
        guideDialog.show(getChildFragmentManager(), "guideDialog");
    }

    private void showCodeDialog(String url, int isUpdate) {

        mUpdateDialog = UpdateDialog.newInstance(isUpdate, false);
        mUpdateDialog.show(getChildFragmentManager(), "mUpdateDialog");
        mUpdateDialog.setmListener(new UpdateDialog.OnItemClickListener() {

            @Override
            public void onConfirm() {
                Intent intent = new Intent();
                intent.setData(Uri.parse(url));//Url 就是你要打开的网址
                intent.setAction(Intent.ACTION_VIEW);
                startActivity(intent); //启动浏览器
                requireActivity().finish();
            }

            @Override
            public void onCancel() {

            }
        });
    }

    public static HomeFragment newInstance() {
        if (homeFragment == null) {
            homeFragment = new HomeFragment();
        }
        return homeFragment;
    }
}
